//
//  TrainOrderListController.swift
//  AirTravel
//
//  Created by apple on 2021/8/24.
//

import UIKit
import Moya
import SwiftyJSON

class TrainOrderListController: UIViewController {

    @IBOutlet weak var tabView: UITableView!
    let identifyLTT = "ListTrainTicketsCell"
    let identifyTOH = "TrainOrderHeaderView"
    let identifyTOF = "TrainOrderFooterView"
    
    
    var intro = 0
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var dataSouce : Array<Any>?
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        
        NotificationCenter.default.addObserver(self, selector: #selector(secondsKillClicks), name: Notification.Name("SecondsKillNotification"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.rowHeight = 80
        self.tabView.separatorStyle = .none
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "ListTrainTicketsCell", bundle: nil), forCellReuseIdentifier: identifyLTT)
        self.tabView.register(UINib.init(nibName: "TrainOrderHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyTOH)
        self.tabView.register(UINib.init(nibName: "TrainOrderFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyTOF)
        
        self.tabView.es.addPullToRefresh {[weak self] in
            self?.getOrderList()
        }
//        self.tabView.es.startPullToRefresh()
//        self.tabView.es.addInfiniteScrolling {[weak self] in
//            self?.getOrderList()
//        }
    }

    //用户火车票订单列表
    func getOrderList() {
        cancelableRequest = NetWorkRequest(API1.getOrderList(parameters: ["status":self.intro]), completion: {[weak self] (responseString) -> (Void) in
            let list = responseString["data"].arrayObject
            self?.dataSouce = list
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }

    @objc func secondsKillClicks(notifi : Notification) {
        let dic = notifi.userInfo
        let i = Int("\(dic?["intro"] ?? "0")") ?? 0
        self.dataSouce = nil
        self.tabView.reloadData()
        self.intro = i
        self.tabView.es.startPullToRefresh()
    }
}

extension TrainOrderListController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int{
        return self.dataSouce?.count ?? 0
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let array = self.dataSouce {
            let dic = array[section] as? Dictionary<String,Any>
            let order_passenger = dic?["order_passenger"] as? Array<Any>
            return order_passenger?.count ?? 0
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifyLTT) as! ListTrainTicketsCell
        cell.selectionStyle = .none
        if let array = self.dataSouce {
            let dic = array[indexPath.section] as? Dictionary<String,Any>
            let departDate = "\(dic?["departDate"] ?? "")"
            let arriveDate = "\(dic?["arriveDate"] ?? "")"
            let departTime = "\(dic?["departTime"] ?? "")"
            let arriveTime = "\(dic?["arriveTime"] ?? "")"
            cell.timeLab.text = departDate + " \(departTime)" + "至" + arriveDate + " \(arriveTime)"
            let trainNo = "\(dic?["trainNo"] ?? "")"
            
            let order_passenger = dic?["order_passenger"] as? Array<Any>
            if let list = order_passenger {
                let dict = list[indexPath.row] as? Dictionary<String,Any>
                let carriageNo = "\(dict?["carriageNo"] ?? "")"
                let seatNo = "\(dict?["seatNo"] ?? "")"
                cell.trainsLab.text = trainNo + " \(carriageNo)车\(seatNo)" + "  \(dict?["name"] ?? "")" + " \(dict?["checkWindow"] ?? "")"
            }
            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 53
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyTOH) as! TrainOrderHeaderView
        ///延迟执行之前的代码
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute:{
            headView.backView.addCorner(conrners: [.topLeft,.topRight], radius: 6)
        })
        headView.contentView.backgroundColor = UIColor.groupTableViewBackground
        if let array = self.dataSouce {
            let dic = array[section] as? Dictionary<String,Any>
            headView.titleLab.text = "\(dic?["fromStationName"] ?? "")-\(dic?["toStationName"] ?? "")"
            let status = "\(dic?["status"] ?? "")"
            switch status {
            case "0":
                headView.stateLab.text = "待支付"
            case "1":
                headView.stateLab.text = "已支付"
            case "2":
                headView.stateLab.text = "支付失败"
            case "3":
                headView.stateLab.text = "待出行"
            case "4":
                headView.stateLab.text = "已出票"
            case "5":
                headView.stateLab.text = "已取消"
            case "6":
                headView.stateLab.text = "已完成"
            default:
                headView.stateLab.text = "出票失败"
            }
        }
        return headView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyTOF) as! TrainOrderFooterView
        ///延迟执行之前的代码
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute:{
            footerView.backView.addCorner(conrners: [.bottomLeft,.bottomRight], radius: 6)
        })
        footerView.contentView.backgroundColor = UIColor.groupTableViewBackground
        if let array = self.dataSouce {
            let dic = array[section] as? Dictionary<String,Any>
            footerView.priceLab.text = "￥\(dic?["orderAmount"] ?? "")"
        }
        return footerView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if let array = self.dataSouce {
            let dic = array[indexPath.section] as? Dictionary<String,Any>
            let vc = TrainOrderDetailsController()
            vc.dataDic = dic
            vc.delegate = self
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
}

extension TrainOrderListController:TrainOrderDetailsDelegate{
    func trainOrderDetailsClick() {
        self.tabView.es.startPullToRefresh()
    }
}
